package com.example.venue_reservation_service.filter;

import java.util.List;

public class SensitiveFilter {
    private final TrieNode root = new TrieNode();
    private static final String REPLACEMENT = "***"; // 敏感词替换字符

    // 构建字典树
    public void buildTrie(List<String> sensitiveWords) {
        for (String word : sensitiveWords) {
            TrieNode currentNode = root;
            // 逐个字符插入树中
            for (char c : word.toCharArray()) {
                TrieNode child = currentNode.getChild(c);
                if (child == null) {
                    child = new TrieNode();
                    currentNode.addChild(c, child);
                }
                currentNode = child;
            }
            currentNode.setEnd(true); // 标记敏感词结尾
        }
    }

    // 敏感词过滤主方法
    public String filter(String text) {
        if (text == null || text.isEmpty()) return text;

        StringBuilder result = new StringBuilder();
        TrieNode currentNode = root;
        int begin = 0; // 当前检测起始位置
        int position = 0; // 当前扫描位置

        while (position < text.length()) {
            char c = text.charAt(position);

            // 特殊字符处理（如空格、符号）
            if (isSymbol(c)) {
                if (currentNode == root) {
                    result.append(c);
                    begin++;
                }
                position++;
                continue;
            }

            // 移动到下一节点
            currentNode = currentNode.getChild(c);

            if (currentNode == null) {
                // 未匹配到敏感词
                result.append(text.charAt(begin));
                position = ++begin;
                currentNode = root; // 重置根节点
            } else if (currentNode.isEnd()) {
                // 发现完整敏感词 → 替换
                result.append(REPLACEMENT);
                begin = ++position;
                currentNode = root;
            } else {
                // 部分匹配，继续扫描
                position++;
            }
        }
        result.append(text.substring(begin)); // 添加剩余文本
        return result.toString();
    }
    // 特殊字符检测（可根据需求扩展）
    private boolean isSymbol(char c) {
        // 过滤非字母数字字符（可自定义规则）
        return !Character.isLetterOrDigit(c) && ((int) c < 0x2E80 || (int) c > 0x9FFF);
    }
}
